package com.bill99.rpc.cluster.loadbalance;

import java.util.List;
import java.util.Random;

import com.bill99.rpc.cluster.ServiceNode;
import com.bill99.rpc.registry.url.ReferenceUrl;

/**
 * 随机：负载均衡方法随机的把负载分配到各个可用的服务器上，通过随机数生成算法选取一个服务器，然后把连接发送给它
 * @author sheng.zhang
 *
 */
public class RandomLoadBalance extends AbstractLoadBalance {

    private final Random random = new Random();
    
    @Override
    public ServiceNode getInvokeServiceNode(List<ServiceNode> serviceNodes,
    		ReferenceUrl referenceUrl) {
    	int length = serviceNodes.size(); // 总个数
        int totalWeight = 0; // 总权重
        boolean sameWeight = true; // 权重是否都一样
        for (int i = 0; i < length; i++) {
            int weight = getWeight(serviceNodes.get(i).getServiceUrl());
            totalWeight += weight; // 累计总权重
            if (sameWeight && i > 0
                    && weight != getWeight(serviceNodes.get(i - 1).getServiceUrl())){
                sameWeight = false; // 计算所有权重是否一样
            }
        }
        if (totalWeight > 0 && ! sameWeight) {
            // 如果权重不相同且权重大于0则按总权重数随机
            int offset = random.nextInt(totalWeight);
            // 并确定随机值落在哪个片断上
            for (int i = 0; i < length; i++) {
                offset -= getWeight(serviceNodes.get(i).getServiceUrl());
                if (offset < 0) {
                    return serviceNodes.get(i);
                }
            }
        }
        // 如果权重相同或权重为0则均等随机
        return serviceNodes.get(random.nextInt(length));
    }

}